/**
 * 注意，这个js文件在测试环境不会生效，会被xvue的同名文件替代掉
 */

import regionAPI from '@/apis/region.js';
import storage from '@/utils/ado-self/ado-storage';

const TYPE = {
  GET_REGIONS: 'Get_Regions',
  GET_ALL_REGIONS: 'Get_All_Regions',
  GET_BRUMB_REGIONS: 'Get_Brumb_Regions',
  SET_CURRENT_REGION: 'Set_Current_Region',
  SET_LOGIN_REGION: 'Set_Login_Region',
  SET_CURRENT_CITY: 'Set_Current_City',
  SET_TOP_REGION: 'Set_Top_Region',
};

const getRegionByCode = (context, code, doSetCurRegion = true) => {
  regionAPI
    .getCurrentRegionPrtChdRegs(code)
    .then(result => {
      if (result && result.length) {
        const regions = context.state.allRegions;
        for (let i = 0; i < result.length; i++) {
          const _region = regions.find(r => String(r.code) === String(result[i].code));
          if (!_region) {
            const newitem = JSON.parse(JSON.stringify(result[i]));
            regions.push(newitem);
          }
        }
        window._adoPremise.regions = regions;
        storage.set('all_regions', regions);
        context.commit(TYPE.GET_REGIONS, regions);
        context.commit(TYPE.GET_ALL_REGIONS, regions);
        if (doSetCurRegion) {
          context.commit(TYPE.SET_CURRENT_REGION, code);
        }

        const curRegionP = regions.find(r => String(r.parentCode) === String(code)) || {};
        if (curRegionP.level > 3) {
          getRegionByCode(context, curRegionP.code, false);
        }
      }
    });
};

export default {
  state: {
    regions: [],
    allRegions: [],
    brumbRegions: [],
    currentRegionCode: '', // GZ0804
    loginRegionCode: '', // GZ0804
    currentCityCode: '',
    topRegion: '',
  },
  mutations: {
    [TYPE.GET_REGIONS](state, payload) {
      state.regions = payload;
    },
    [TYPE.GET_ALL_REGIONS](state, payload) {
      state.allRegions = payload;
    },
    [TYPE.GET_BRUMB_REGIONS](state, payload) {
      state.brumbRegions = payload;
    },
    [TYPE.SET_CURRENT_REGION](state, payload) {
      state.currentRegionCode = payload;
    },
    [TYPE.SET_LOGIN_REGION](state, payload) {
      state.loginRegionCode = payload;
    },
    [TYPE.SET_CURRENT_CITY](state, payload) {
      state.currentCityCode = payload;
    },
    [TYPE.SET_TOP_REGION](state, payload) {
      state.topRegion = payload;
    },
  },
  actions: {
    getRegions(context, params, getRegionsComplete) {
      return new Promise((resolve, reject) => {
        try {
          regionAPI
            .getRegionsByApi(params)
            .then(res => {
              if (res && res.data) {
                const _data = res.data.data;
                const op = {
                  apiCode: 'getRegion',
                  params: [
                    {
                      code: 'level',
                      value: 2,
                    },
                    {
                      code: 'parent_code',
                      value: 'SD',
                    },
                  ],
                };
                regionAPI.getRegionsByApi(op).then(result => {
                  if (result && result.data) {
                    const _res = result.data.data;
                    const frs = [..._data, ..._res];
                    context.commit(TYPE.GET_REGIONS, frs);
                    resolve(frs);
                  }
                });
              }
            })
            .catch(err => {
              reject(err);
            });
        } catch (err) {
          reject(err);
        }
      });
    },
    getBrumbRegions(context, { regions, regionCode, loginRegionCode, isNoSync, getBrumbRegionsCompleted }) {
      if (!regionCode || !loginRegionCode) {
        return;
      }

      let brumbRegions = [];
      const forbiddenRegions = [];

      // 找出自己及父区域
      const findParentRegion = (_regionCode, optRegions) => {
        const region = regions.find(r => r.code === _regionCode);
        if (region) {
          optRegions.push(region);
          if (region.parentCode) {
            findParentRegion(region.parentCode, optRegions);
          }
        }
      };

      // 查找面包屑
      findParentRegion(regionCode, brumbRegions);

      // 找出该账号禁止点击的region
      const loginRegion = regions.find(r => r.code === loginRegionCode);
      let loginParentRegion = null;
      if (loginRegion && loginRegion.parentCode) {
        loginParentRegion = regions.find(r => r.code === loginRegion.parentCode);
      }
      if (loginParentRegion && loginParentRegion.parentCode) {
        findParentRegion(loginParentRegion.parentCode, forbiddenRegions);
      }

      // 可查看的区域权限
      if (brumbRegions.length) {
        for (let jj = 0; jj < brumbRegions.length; jj++) {
          brumbRegions[jj].canClick = true;
          if (forbiddenRegions && forbiddenRegions.length) {
            const item = brumbRegions[jj];
            const brRegion = forbiddenRegions.find(r => String(r.code) === String(item.code));
            brumbRegions[jj].canClick = !brRegion;
          }
        }
      }

      // 按从父到子进行区域输出
      const temp = [];
      if (brumbRegions.length) {
        for (let ii = brumbRegions.length - 1; ii > -1; ii--) {
          temp.push(brumbRegions[ii]);
        }
        brumbRegions = temp;
      }
      if (!isNoSync) {
        context.commit(TYPE.GET_BRUMB_REGIONS, brumbRegions);
      }
      if (getBrumbRegionsCompleted) {
        getBrumbRegionsCompleted(brumbRegions);
      }
    },
    getGDBrumbRegions(context, { regions, regionCode, loginRegionCode, isNoSync, getBrumbRegionsCompleted }) {
      if (!isNoSync) {
        context.commit(TYPE.GET_BRUMB_REGIONS, []);
      }
      if (!regionCode || !loginRegionCode) {
        return;
      }

      let brumbRegions = [];
      const forbiddenRegions = [];

      // 找出自己及父区域
      const findParentRegion = (_regionCode, optRegions) => {
        const region = regions.find(r => r.code === _regionCode);
        if (region) {
          optRegions.push(region);
          if (region.parent_code) {
            findParentRegion(region.parent_code, optRegions);
          }
        }
      };

      // 查找面包屑
      findParentRegion(regionCode, brumbRegions);

      // 找出该账号禁止点击的region
      const loginRegion = regions.find(r => r.code === loginRegionCode);
      let loginParentRegion = null;
      if (loginRegion && loginRegion.parent_code) {
        loginParentRegion = regions.find(r => r.code === loginRegion.parent_code);
      }
      if (loginParentRegion && loginParentRegion.parent_code) {
        findParentRegion(loginParentRegion.parent_code, forbiddenRegions);
      }

      // 可查看的区域权限
      if (brumbRegions.length) {
        for (let j = 0; j < brumbRegions.length; j++) {
          brumbRegions[j].canClick = true;
          if (forbiddenRegions && forbiddenRegions.length) {
            const item = brumbRegions[j];
            const brRegion = forbiddenRegions.find(r => String(r.code) === String(item.code));
            brumbRegions[j].canClick = !brRegion;
          }
        }
      }

      // 按从父到子进行区域输出
      const temp = [];
      if (brumbRegions.length) {
        for (let i = brumbRegions.length - 1; i > -1; i--) {
          temp.push(brumbRegions[i]);
        }
        brumbRegions = temp;
      }
      if (getBrumbRegionsCompleted) {
        getBrumbRegionsCompleted(brumbRegions);
      }
      if (!isNoSync) {
        context.commit(TYPE.GET_BRUMB_REGIONS, brumbRegions);
      }
    },
    getAllRegions(context) {
      context.commit(TYPE.GET_ALL_REGIONS, window._adoPremise.regions || storage.get('all_regions'));
    },
    setCurrentRegion(context, code) {
      if (!code) {
        return;
      }
      getRegionByCode(context, code);
    },
    setGDCurrentRegion(context, code) {
      context.commit(TYPE.SET_CURRENT_REGION, code);
    },
    setLoginRegion(context, code) {
      context.commit(TYPE.SET_LOGIN_REGION, code);
    },
    setCurrentCity(context, cityCode) {
      context.commit(TYPE.SET_CURRENT_CITY, cityCode);
    },
  },
};
